package com.xjscrm.console.aop;

import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.xjscrm.common.utils.DateUtil;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.lang.reflect.Field;

/**
 * <p>
 * 入库数据统一设置公共参数
 * </p>
 */
@Aspect
@Component
public class MapperAop {

    private static Logger logger = LoggerFactory.getLogger(MapperAop.class);

    private static final String ADD_POINTCUT = "execution(public * com.xjscrm.console.mapper..*.add*(..))";
    private static final String UPDATE_POINTCUT = "execution(public * com.xjscrm.console.mapper..*.update*(..))";


    @Before(UPDATE_POINTCUT)
    public Object doUpdateAround(JoinPoint joinPoint) throws Throwable {
        Object[] objects = joinPoint.getArgs();
        Object object = objects[0];
        Class clazz = object.getClass();

        while (clazz != null) {
            try {
                Field updateTimeField = clazz.getSuperclass().getDeclaredField("updateTime");
                updateTimeField.setAccessible(true);
                updateTimeField.set(object, DateUtil.getTime());
                break;
            } catch (Exception e) {
//                logger.error("err:", e);
                clazz = clazz.getSuperclass();
            }
        }


        return object;
    }

    @Before(ADD_POINTCUT)
    public Object doAddAround(JoinPoint joinPoint) throws Throwable {
        Object[] objects = joinPoint.getArgs();
        Object object = objects[0];

        int time = DateUtil.getTime();


        Class clazz = object.getClass();
        while (clazz != null) {
            try {
                Field updateTimeField = clazz.getSuperclass().getDeclaredField("updateTime");
                updateTimeField.setAccessible(true);
                updateTimeField.set(object, time);

                Field createTimeField = clazz.getSuperclass().getDeclaredField("createTime");
                createTimeField.setAccessible(true);
                createTimeField.set(object, time);

                Field idField = clazz.getSuperclass().getDeclaredField("id");
                idField.setAccessible(true);
                Long id = IdWorker.getId();
                idField.set(object, id);
                break;
            } catch (Exception e) {
//                logger.error("err:", e);
                clazz = clazz.getSuperclass();
            }
        }
        return object;
    }
}
